import { Provide, Inject, Context } from "@midwayjs/core";
import { JwtService } from "@midwayjs/jwt";

@Provide()
export class TokenService {
  @Inject()
  jwtService: JwtService;

  @Inject()
  ctx: Context;

  // 获取token
  async getToken(payload) {
    // 设置token过期时间
    const expiresIn = 60 * 5;
    return this.jwtService.signSync({ payload }, { expiresIn });
  }

  // 刷新token
  async refreshToken(oldToken) {
    await this.jwtService.verifySync(oldToken.toString(), {
      complete: true,
    });

    const uniqueKey = `myRefreshToken/${Date.now()}${Math.random()
      .toString(36)
      .substring(2)}`;

    const expiresIn = 60 * 5;
    const newToken = this.jwtService.signSync({ uniqueKey }, { expiresIn });
    return {
      token: newToken,
    };
  }
}
